from django.contrib import admin

# Register your models here.
# 注册历史记录(后台管理)
from .models import DiagnosisHistory
from django.utils.html import format_html


# admin.site.register(DiagnosisHistory)
# 基本配置DiagnosisHistory,admin操作, 用类的高阶方式
@admin.register(DiagnosisHistory)
class DiagnosisHistoryAdmin(admin.ModelAdmin):
    list_display = (
        "user",
        "diagnosis_date",
        "diagnosis_result",
        # "prediction_rates",
        "format_prediction_rates",  # 用函数自动加载优化样式
        "notes",
    )
    list_filter = (
        "user",
        "diagnosis_date",
        "diagnosis_result",
        "notes",
    )  # 过滤器 用于筛选数据
    search_fields = (
        "user__username", # Changed from "user" to "user__username" to search the username field 
                         # Django's search_fields doesn't support searching on ForeignKey fields directly
                         # We need to use the double underscore syntax to search on related fields
        "diagnosis_date",
        "diagnosis_result", 
        "notes",
    )
    date_hierarchy = "diagnosis_date"
    ordering = ("-diagnosis_date",)

    # prediction 表示样式优化
    def format_prediction_rates(self, obj):
        # Customize the display of prediction_rates
        formatted_rates = "  |  ".join(
            [f"{key}: {value}%" for key, value in obj.prediction_rates.items()]
        )
        # 这种不会被xss攻击,因为是后台管理系统没有输入框
        return format_html('<span style="color: green;">{}</span>', formatted_rates)

    format_prediction_rates.short_description = "预测率"  # 设置表头名称
